package cz.data.domain.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import cz.data.common.mybatis.BaseServiceImpl;
import cz.data.common.core.DataConstant;
import cz.data.common.rabbitmq.config.RabbitConstant;
import cz.data.domain.market.dao.TableApiDao;
import cz.data.domain.market.mapstruct.TableApiMapper;
import cz.data.domain.market.model.dto.ApiChangeMessage;
import cz.data.domain.market.model.dto.TableApiDto;
import cz.data.domain.market.model.entity.TableApiEntity;
import cz.data.domain.market.service.TableApiService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TableApiServiceImpl extends BaseServiceImpl<TableApiDao, TableApiEntity>
        implements TableApiService {

    @Resource
    TableApiMapper tableApiMapper;
    @Resource
    RabbitTemplate rabbitTemplate;

    @Override
    public TableApiEntity getTableApiById(String id) {
        return getById(id);
    }

    @Override
    public boolean saveTableApi(TableApiDto api) {
        TableApiEntity tableApi = tableApiMapper.toEntity(api);
        return save(tableApi);
    }

    @Override
    public boolean updateTableApi(TableApiDto api) {
        TableApiEntity tableApi = tableApiMapper.toEntity(api);
        return updateById(tableApi);
    }

    @Override
    public boolean deleteTableApi(List<String> ids) {
        boolean success = false;
        for (String id : ids) {
            boolean removed = removeById(id);
            if (removed) {
                success = true;
            }
        }
        return success;
    }

    @Override
    public boolean updateTableApiStatus(String id, String status) {
        UpdateWrapper<TableApiEntity> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(TableApiEntity::getId, id);
        wrapper.lambda().set(TableApiEntity::getStatus, status);
        boolean update = update(wrapper);
        if (update) {
            if (DataConstant.ApiState.RELEASE.getKey().equals(status)) {
                rabbitTemplate.convertAndSend(RabbitConstant.API_FANOUT_EXCHANGE, "",
                        ApiChangeMessage.fromTableApi(id, ApiChangeMessage.RELEASE));
            } else {
                rabbitTemplate.convertAndSend(RabbitConstant.API_FANOUT_EXCHANGE, "",
                        ApiChangeMessage.fromTableApi(id, ApiChangeMessage.CANCEL));
            }
        }
        return update;
    }
}
